#pragma once
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <pthread.h>
#include <string>
#include <functional>
#include <queue>
#define NUM 5

template <class T>
class BlockQueue
{
    private:
    bool IsFull()
    {
        return _queue.size() >= _cp;
    }
public:
    BlockQueue()
        : _cp(NUM), _psleep_num(0), _csleep_num(0)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_empty_cond,nullptr);
        pthread_cond_init(&_full_cond,nullptr);
    }

    void Equeue(T data)
    {
        pthread_mutex_lock(&_mutex);
        while (IsFull())
        {
            _psleep_num++;
            pthread_cond_wait(&_full_cond,&_mutex);
            _psleep_num--;
        }
        _queue.push(data);
        if(_csleep_num > 0)
        pthread_cond_signal(&_empty_cond);
        pthread_mutex_unlock(&_mutex);
    }
    T Pop()
    {
        pthread_mutex_lock(&_mutex);
        while (_queue.empty())
        {
            _csleep_num++;
            pthread_cond_wait(&_empty_cond,&_mutex);
            _csleep_num--;
        }
        T ret = _queue.front();
        _queue.pop();
        if(_psleep_num > 0)
        pthread_cond_signal(&_full_cond);
        pthread_mutex_unlock(&_mutex);
        return ret;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_empty_cond);
        pthread_cond_destroy(&_full_cond);
    }

private:
    std::queue<T> _queue;
    int _cp;
    pthread_mutex_t _mutex;
    pthread_cond_t _empty_cond;
    pthread_cond_t _full_cond;

    int _psleep_num; // 生产者睡眠数量
    int _csleep_num; // 消费者睡眠数量
};